import React from 'react'
import { info, success, Tabs, Button, Link, Table, TitleBar, Modal } from '../../../ui-components'
import { connect } from 'react-redux'
import style from './style.onboardingFlows'
import util from '../../../util'
import moment from 'moment'
import cx from 'classnames'
import { map as tableMap } from '../../../ui-components/table'
import { u } from '../../../actions/util'
import userStatus from '../../../constants/userStatus'

export
const ONBOARDING_STATUS = {
  "1": "等待员工填写资料",
  "2": "员工已提交资料",
  "3": "资料已审核"
}

export default
@connect(({ onboardingFlowsHr }) => ({ onboardingFlowsHr }))
class OnboardingFlows extends React.Component {

  state = {
    invitationDialog: false,
    invitedEmailAddress: '',
    deleteStaff: false
  }

  readyDelStaff = {}

  handleCopy() {
    const el = this.refs.invitationUrl
    el.select()
    const ret = document.execCommand('copy')
    if (ret) {
      info('已复制到剪贴板!')
    } else {
      info('您的浏览器不支持复制到剪贴板!')
    }
  }

  deleteStaff() {
    info('撤销入职中..', true)
    this.props.delStaff(this.readyDelStaff.userId, () => {
      success('撤销入职成功!')
      this.fetchOnboardingFlows()
    })
    this.setState({
      deleteStaff: false
    })
  }

  pageNumber=1
  pageSize=30

  handleTab() {}

  invitedUser={}

  handleDelStaff(user) {
    this.readyDelStaff = user
    this.setState({
      deleteStaff: true
    })
  }

  handlePageChage(_pageNumber) {
    const { pageNumber, ...others } = this.props.location.query
    this.props.router.push(`/hr/onboarding/onboarding-flows?pageNumber=${_pageNumber}&${util.body(others)}`)
  }

  fetchOnboardingFlows(props) {
    props = props || this.props
    const pageNumber = props.location.query.pageNumber || this.pageNumber

    info('读取中..', true)
    this.props.fetchOnboardingFlows({
      pageNumber,
      pageSize: this.pageSize,
      hasApproved: props.location.query.hasApproved
    }, () => {
      info()
    })
  }

  componentWillUnmount() {
    this.props.resetOnboardingFlows();
  }

  componentWillReceiveProps(props) {
    if (props.location.query.hasApproved != this.props.location.query.hasApproved) {
      this.fetchOnboardingFlows(props)
    }
  }

  componentDidMount() {
    this.fetchOnboardingFlows()
  }

  sendInvitationEmail() {
    this.props.resendInvitation(this.invitedUser.userId, () => {
      success('发送成功!')
    })
  }

  closeInvitationDialog() {
    // clear
    this.setState({
      invitedEmailAddress: ''
    })

    util.dialog.call(this, 'invitationDialog')
  }

  requestInvite(user) {
    this.invitedUser = user
    this.props.fetchInvitationUrl(user.userId)
    util.dialog.call(this, 'invitationDialog')
  }

  updateOnboardingFlowStatus() {
    this.props.updateOnboardingFlowStatus.apply(this, arguments)
  }

  render() {
    const { flows } = this.props.onboardingFlowsHr
    const { coreUserProfileVOs:list, totalNumber } = flows
    const tableConfig = {
      pagin: typeof totalNumber === 'number' && {
        pageSize: this.pageSize,
        pageNumber: this.props.location.query.pageNumber || this.pageNumber,
        totalNumber,
        onChange: ::this.handlePageChage,
        fetch: ::this.fetchOnboardingFlows
      },
      data: list,
      model: {
        fullName: '新成员',
        jobTitleName: '职位',
        createdTime: '发起时间',
        enrollDate: '入职时间',
        onboardingStatus: '状态',
        others: ''
      },
      config: {
        jobTitleName: '.4',
        enrollDate: '.5',
        createdTime: '.5',
        onboardingStatus: '.4'
      },
      map: {
        fullName: tableMap.fullName,
        createdTime: v => util.time(v),
        enrollDate: v => util.time(v),
        others: (value, user) => {
          const { onboardingStatus } = user.userEmploymentVO
          const userStatusiDecr = userStatus(user.userEmploymentVO)
          return (
            <div data-role='table-hover' className={style.others}>
              {
                (userStatusiDecr === '待入职' && !util.isEqual(user.userId, u.userId))?
                <Link label="撤销入职" color="red" onClick={() => this.handleDelStaff(user)}/>: null
              }
              {
                onboardingStatus == 1?
                <Link label="邀请入职" onClick={() => this.requestInvite(user)}/>
                :null
              }
              {
                !util.isEqual(user.userId, u.userId)?
                <Link style={onboardingStatus == 2? { opacity: '1' }: {}} label={onboardingStatus == 2? "审核资料": "编辑"} to={`#/hr/team-memeber-edit/${user.userId}?tab=2`}/>: null
              }
            </div>
          )
        },
        onboardingStatus: (value, item) => <span className={cx({
          [style['status-' + item.userEmploymentVO.onboardingStatus]]: true,
          [style.status]: true
        })}>{ ONBOARDING_STATUS[item.userEmploymentVO.onboardingStatus]  }</span>
      }
    }
    const { hasApproved } = this.props.location.query
    return (
      <div className={style.root}>
        <TitleBar
          label={hasApproved == 0? "入职处理中": "已处理"}
          actions={[{
            label: '发起新入职',
            handler: () => this.props.router.push('/hr/onboarding/onboarding-create')
          }]}
        />
        <Table
          {...tableConfig}
        />
        <Modal
          active={this.state.invitationDialog}
          onRequestClose={::this.closeInvitationDialog}
          title="将入职邀请链接发送给新员工"
          actions={['cancel']}
        >
          <div className={style.invitationDialogBody}>
            <div>
              <p>
                <span>1.</span>
                <span>邮件发送</span>
              </p>
              <p>
                <span>{this.invitedUser.emailAddress}</span>
                <Button label="立即发送" onClick={::this.sendInvitationEmail}/>
              </p>
            </div>
            <div>
              <p>
                <span>2.</span>
                <span>其他方式发送</span>
              </p>
              <p>
                <input ref="invitationUrl" value={ (this.props.onboardingFlowsHr.invitationUrl || '')+'#/onboarding/staff/welcome'} onChange={() => {}}/>
                <Button label="复制链接" onClick={::this.handleCopy}/>
              </p>
            </div>
          </div>
        </Modal>
        <Modal
          active={this.state.deleteStaff}
          onRequestClose={() => this.setState({ deleteStaff: false })}
          actions={[
            'cancel',
            ::this.deleteStaff
          ]}
          title="撤销入职"
        >
          <div>
            <p>确定撤销入职并删除该员工吗?</p>
          </div>
        </Modal>
      </div>
    )
  }
}
